#include "connector.h"


using namespace lvpublisher;
using namespace smartBuffer;


Connector::Connector()
{

}

Connector::Connector(int fd)
    : m_fd(fd)
{

}

Connector::~Connector()
{

}

void Connector::setfd(int fd)
{
    m_fd = fd;
}

bool Connector::sendData(const char * src, size_t n)
{
    if(m_fd == -1) return false;
    ssize_t ret = send(m_fd, src, n, 0);
    if(ret == -1)
    {
        return false;
    }
    return true;
}

SmartBuffer Connector::recvData()
{
    SmartBuffer out;
    int recved = 0;
    size_t oneTimeLength = 1460 * 10;
    unique_ptr<char> buf(new char[oneTimeLength]);
    while(1)
    {
        ssize_t ret = recv(m_fd, buf.get(), oneTimeLength, 0);
        if(ret < 0)
        {
            throw std::exception();
        }
        recved += (int)ret;
        out.add(buf.get(), ret);
        if(ret < oneTimeLength)
        {
            break;
        }
    }
    return out;
}

smartBuffer::SmartBuffer Connector::recvData(size_t size)
{
    SmartBuffer out(size);
    int recved = 0;
    size_t oneTimeLength = 1460 * 10;
    while(1)
    {
        ssize_t ret = recv(m_fd, out.getPtr() + recved, oneTimeLength, 0);
        if(ret < 0)
        {
            throw std::exception();
        }
        recved += (int)ret;
        if(recved == size)
        {
            break;
        }
    }
    return out;
}

bool Connector::sendFile(int fd_in)
{
    if(fd_in == -1) return false;
    struct stat st;
    fstat(fd_in, &st);
    int ret = sendfile64(m_fd, fd_in, nullptr, st.st_size);
    if(ret == -1)
    {
        return false;
    }
    return true;
}


